import json
import requests

def getYiQing(province):
    provinceName = province
    todayKey = 'today'
    totalKey = 'total'
    confirmKey = 'confirm'
    nowConfirmKey = 'nowConfirm'
    suspectKey = 'suspect'
    nameKey = 'name'
    childrenKey = 'children'

    # 腾讯实时疫情接口api接口
    api = 'https://view.inews.qq.com/g2/getOnsInfo?name=disease_h5'

    datas = json.loads(requests.get(url=api).json()['data'])
    #最新更新时间 dataLog
    dataLog = datas['lastUpdateTime']

    #获取国内新增确诊、现有确诊、疑似病例数
    for contry in datas['areaTree']:
        if contry[nameKey] == '中国':
            for province in contry[childrenKey]:
                if province[nameKey] == provinceName:
                    newConfirm = str(province[todayKey][confirmKey])
                    nowConfirm = str(province[totalKey][nowConfirmKey])
                    nowSuspect = str(province[totalKey][suspectKey])
                    
    return dataLog, newConfirm, nowConfirm, nowSuspect
                       

if __name__ == '__main__':
    prov = '广东'
    yiqing = getYiQing(prov)
    updatetime = yiqing[0]
    newconfirm = yiqing[1]
    nowconfirm = yiqing[2]
    nowsuspect = yiqing[3]
    yiqingdate = {'省份':prov, '新增确诊':newconfirm, '现有确诊':nowconfirm, '疑似':nowsuspect, '更新时间':updatetime}
    print(yiqingdate)

    filename = 'yiqing.json'
    with open(filename, 'w', encoding='utf-8') as file_obj:
        json.dump(yiqingdate, file_obj, ensure_ascii=False)